package project;
import java.util.ArrayList;
import java.sql.*;

public class RecordInfo {

private DatabaseInfo database;
private String tableName;
private int entryNum;
public ArrayList<Object> attributes = new ArrayList<Object>();

public RecordInfo(){
    database = new DatabaseInfo();
    tableName = new String();
}
public RecordInfo(DatabaseInfo db,  int position){
    int entry = position;
        try {
           Class.forName("com.mysql.jdbc.Driver").newInstance();
	} catch (Exception e) {
            System.err.println("Error loading Driver");
	}
    Connection conn = null;
    try{
        conn = DriverManager.getConnection("jdbc:mysql://" + db.getHostName()+":"+db.getPortNo()+"/"+db.getDatabaseName(),
		db.getUserName(),db.getPassword());
        Statement stmt = conn.createStatement();
        ResultSet tables = conn.getMetaData().getTables("", "", "", null);
        ResultSet record = null;
    while (tables.next()) {
        ResultSet rows = stmt.executeQuery("select count(*) from "+ tables.getString(3));
        rows.absolute(1);
        int rowNum = Integer.parseInt(rows.getString(1));
        //entry = position;//(rowNum * position) / fraction;
        if (rowNum < entry) {
            entry -= rowNum;
        } else {
        record = stmt.executeQuery("Select * from "+ tables.getString(3) + " limit "  + (entry-1) + ",1");
        break;
        }
    }
        database = db;
        tableName = tables.getString(3);
        entryNum = entry;
        record.first();
        //record.absolute(entry);
//        System.out.println(database.getDatabaseName()+ ", " + tableName);
        int i = 1;
        while (true){
            try{
//            System.out.print(record.getString(i) + " ");
            attributes.add((Object)record.getString(i));
            i++;
            } catch (Exception e){
 //               System.out.println();
                break;
            }
        }

    } catch (SQLException e){
        System.err.println(e.getMessage());
    }
}

public String getTableName(){
    return tableName;
}

public int getEntryNum(){
    return entryNum;
}

public DatabaseInfo getDatabase(){
    return database;
}

public ArrayList getAttributes(){
    return attributes;
}

public Object getAttribute(int i){
    return attributes.get(i);
}
public void copyInfo(DatabaseInfo db, String table, int entry){
    database = db;
    tableName = table;
    entryNum = entry;
}

}
